<script setup lang="ts">
import EChartsComponent from "@/components/EChartsComponent/index.vue";
import "plus-pro-components/es/components/search/style/css";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import { computed, onMounted, ref } from "vue";
import { getDataBySQLDesc } from "@/api/common";
import { usePagination } from "@/hooks/usePagination";
import moment from "moment";
defineOptions({
  name: "EarlyDelivery"
});
const pagination = usePagination();
const searchColumns: PlusColumn[] = [
  {
    label: "年份",
    prop: "dhnd",

    valueType: "date-picker",
    fieldProps: {
      type: "year",
      valueFormat: "YYYY",
      placeholder: "请选择年份"
    }
  },
  {
    label: "到货开始时间",
    prop: "kssj",
    labelWidth: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "date",
      valueFormat: "YYYY-MM-DD",
      placeholder: "请选择开始时间"
    }
  },
  {
    label: "到货结束时间",
    prop: "jssj",
    labelWidth: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "date",
      valueFormat: "YYYY-MM-DD",
      placeholder: "请选择结束时间"
    }
  }
];
const option = computed(() => {
  return {
    tooltip: {
      trigger: "axis",
      position: function (point, params, dom, rect, size) {
        // point: 鼠标位置，格式为 [x, y]
        // params: 提示框所包含的数据信息
        // dom: 提示框的 DOM 元素
        // rect: 鼠标所在图形的包围盒，格式为 {x, y, width, height}
        // size: 提示框的大小，格式为 {contentSize: [width, height], outerSize: [width, height]}
        return [point[0] - 50, point[1] - 50]; // 设置提示框在鼠标上方 20px 处
      },
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999"
        }
      }
    },
    legend: {
      type: "scroll",
      data: [
        "应到批次",
        "全货到货批次",
        "全货入库批次",
        "全货到货率",
        "全货入库率"
      ]
    },
    xAxis: [
      {
        type: "category",
        data: [
          "一月",
          "二月",
          "三月",
          "四月",
          "五月",
          "六月",
          "七月",
          "八月",
          "九月",
          "十月",
          "十一月",
          "十二月"
        ],
        axisPointer: {
          type: "shadow"
        }
      }
    ],
    yAxis: [
      {
        type: "value",
        axisLabel: {
          formatter: "{value}"
        }
      },
      {
        type: "value",
        axisLabel: {
          formatter: "{value}%"
        }
      }
    ],
    series: seriesData.value
  };
});
const seriesData = computed(() => {
  let arr = [];
  let nameList = [
    "应到批次",
    "全货到货批次",
    "全货入库批次",
    "全货到货率",
    "全货入库率"
  ];
  nameList.map((item, index) => {
    let obj = {
      name: item,
      type: index > 2 ? "line" : "bar",
      smooth: true,
      yAxisIndex: index > 2 ? 1 : 0,
      tooltip: {
        valueFormatter: function (value) {
          if (index > 2) {
            return value.toFixed(2) + "%";
          } else {
            return value;
          }
        }
      },
      data: []
    };
    yearTableData.value.map(item1 => {
      if (index > 2) {
        obj.data.push(item1[item] * 100);
      } else {
        obj.data.push(item1[item]);
      }
    });
    arr.push(obj);
  });
  return arr;
});
const columns = computed(() => [
  {
    label: "项目",
    prop: "project"
  },

  {
    label: form.value.dhnd + "年Q1",
    children: [
      { label: "一月", prop: "jan" },
      { label: "二月", prop: "feb" },
      { label: "三月", prop: "mar" }
    ]
  },
  {
    label: form.value.dhnd + "年Q2",
    children: [
      { label: "四月", prop: "apr" },
      { label: "五月", prop: "may" },
      { label: "六月", prop: "jun" }
    ]
  },
  {
    label: form.value.dhnd + "年Q3",
    children: [
      { label: "七月", prop: "jul" },
      { label: "八月", prop: "aug" },
      { label: "九月", prop: "sep" }
    ]
  },
  {
    label: form.value.dhnd + "年Q4",
    children: [
      { label: "十月", prop: "oct" },
      { label: "十一月", prop: "nov" },
      { label: "十二月", prop: "dec" }
    ]
  }
]);
// 新增响应式数据，用于存储从接口获取的数据
const columns2 = computed(() => [
  {
    label: "采购到厂日期",
    prop: "采购到厂日期"
  },
  {
    label: "全货到货批次",
    prop: "全货到货批次"
  },
  {
    label: "应到批次",
    prop: "应到批次"
  },
  {
    label: "全货到货率",
    prop: "全货到货率"
  }
]);
const columns3 = computed(() => [
  {
    label: "供应商",
    prop: "供应商"
  },
  {
    label: "应到批次",
    prop: "应到批次"
  },
  {
    label: "按时到货批次",
    prop: "按时到货批次"
  },

  {
    label: "提前到货批次",
    prop: "提前到货批次"
  },
  {
    label: "全货到货批次",
    prop: "全货到货批次"
  },
  {
    label: "全货到货率",
    prop: "全货到货率"
  }
]);
const columns4 = computed(() => [
  {
    label: "采购批次",
    prop: "采购批次"
  },
  {
    label: "要求到厂日期",
    prop: "要求到库日期"
  },

  {
    label: "批次采购数量",
    prop: "批次采购数量"
  },
  {
    label: "批次到货数量",
    prop: "批次到货数量"
  },
  {
    label: "收货数量",
    prop: "收货数量"
  },
  {
    label: "入库数量",
    prop: "入库数量"
  },
  {
    label: "收货审核日期",
    prop: "收货审核日期"
  },
  {
    label: "执行状态",
    prop: "执行状态"
  }
]);
const providerTableData = ref([]);
const showProviderDetail = ref(false);
const providerDetailList = ref([]);
const providerForm = ref({
  gys: "",
  gysNmae: ""
});
const yearTableData = ref([]);
const lastYearTableData = ref([]);
const monthListData = ref([]);
const showMonthTableDetail = ref(false);
const monthForm = ref({
  date: "",
  kssj: "",
  jssj: ""
});
const data = computed(() => {
  let arr = [
    "应到批次",
    "全货到货批次",
    "全货到货率",
    Number(form.value.dhnd) - 1 + "年全货率"
  ];
  let result = [];
  arr.map(item => {
    result.push({
      project: item,
      jan: "",
      feb: "",
      mar: "",
      apr: "",
      may: "",
      jun: "",
      jul: "",
      aug: "",
      sep: "",
      oct: "",
      nov: "",
      dec: ""
    });
  });
  let arr1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
  let arr2 = [
    "jan",
    "feb",
    "mar",
    "apr",
    "may",
    "jun",
    "jul",
    "aug",
    "sep",
    "oct",
    "nov",
    "dec"
  ];
  // 根据 apiData 更新 result
  yearTableData.value.map(item => {
    let index = arr1.indexOf(item.采购到库月份);
    if (index > -1) {
      result[0][arr2[index]] = item.应到批次;
      result[1][arr2[index]] = item.全货到货批次;
      result[2][arr2[index]] = item.全货到货率 * 100 + "%";
    }
  });
  lastYearTableData.value.map(item => {
    let index = arr1.indexOf(item.采购到库月份);
    if (index > -1) {
      result[3][arr2[index]] = item.全货到货率 * 100 + "%";
    }
  });
  return result;
});

const form = ref({
  dhnd: "",
  kssj: "",
  jssj: "",
  gys: "",
  gysNmae: ""
});
// 获取年份
const getTime = async () => {
  const { data } = await getDataBySQLDesc({
    action: "public/get_server_sysdate"
  });
  form.value.dhnd = data[0].年;
  getYearTable();
  getLastYearTable();
};
const handleCellClick = async (row, column, cell, event) => {
  let arr = [
    "一月",
    "二月",
    "三月",
    "四月",
    "五月",
    "六月",
    "七月",
    "八月",
    "九月",
    "十月",
    "十一月",
    "十二月"
  ];
  const monthIndex = arr.findIndex(item => item === column.label);
  console.log(monthIndex);
  if (monthIndex < 0) return;
  let month = monthIndex + 1;
  const startTime = moment(form.value.dhnd + "-" + month + "-01")
    .startOf("month")
    .format("YYYY-MM-DD HH:mm:ss");
  const endTime = moment(form.value.dhnd + "-" + month + "-01")
    .endOf("month")
    .format("YYYY-MM-DD HH:mm:ss");
  const params = {
    action: "biz/reports/get_tqdh_zdsj_gys_pctj",
    kssj: startTime,
    jssj: endTime
  };
  monthForm.value.kssj = startTime;
  monthForm.value.jssj = endTime;
  const { data } = await getDataBySQLDesc(params);
  monthListData.value = data;
  monthListData.value.map(e => {
    e["全货到货率"] = (e["全货到货率"] * 100).toFixed(2) + "%";
  });
  showMonthTableDetail.value = true;
};
const handleCellClick2 = async (row, column, cell, event) => {
  providerForm.value.gys = row["供应商编号"];
  providerForm.value.gysNmae = row["供应商"];
  let params = {
    action: "biz/reports/get_tqdh_zdsj_zdgys_pctjmx",
    kssj: form.value.kssj ? form.value.kssj + " 00:00:00" : "",
    jssj: form.value.jssj ? form.value.jssj + " 23:59:59" : "",
    gys: providerForm.value.gys
  };
  const { data } = await getDataBySQLDesc(params);
  providerDetailList.value = data;
  providerDetailList.value.map(e => {
    e["全货到货率"] = (e["全货到货率"] * 100).toFixed(2) + "%";
  });
  showProviderDetail.value = true;
};
const recoverFn2 = () => {
  providerForm.value.gys = "";
  providerForm.value.gysNmae = "";
  providerDetailList.value = [];
  showProviderDetail.value = false;
};
const recoverFn1 = () => {
  monthListData.value = [];
  showMonthTableDetail.value = false;
};
const handleSearch = () => {
  showMonthTableDetail.value = false;
  showProviderDetail.value = false;
  pagination.currentPage = 1;
  getYearTable();
  getLastYearTable();
  getProviderTable();
};
const handleRest = () => {
  form.value.kssj = "";
  form.value.jssj = "";
  pagination.currentPage = 1;
  getTime();
};
const getProviderTable = async () => {
  let params = {
    action: "biz/reports/get_tqdh_zdsj_mr_pctj",
    kssj: form.value.kssj ? form.value.kssj + " 00:00:00" : "",
    jssj: form.value.jssj ? form.value.jssj + " 23:59:59" : "",
    pageindex: pagination.currentPage.toString(),
    pagesize: pagination.pageSize.toString()
  };
  const { data, total } = await getDataBySQLDesc(params);
  pagination.total = total;
  providerTableData.value = data;
  providerTableData.value.map(e => {
    e["全货到货率"] = (e["全货到货率"] * 100).toFixed(2) + "%";
  });
};
const getYearTable = async () => {
  let params = {
    action: "biz/reports/get_tqdh_my_pctj",
    dhnd: form.value.dhnd
  };
  const { data } = await getDataBySQLDesc(params);
  yearTableData.value = data;
};
const getLastYearTable = async () => {
  let dhnd = Number(form.value.dhnd) - 1;
  let params = {
    action: "biz/reports/get_tqdh_my_pctj",
    dhnd: dhnd + ""
  };
  const { data } = await getDataBySQLDesc(params);
  lastYearTableData.value = data;
};
const changePagination = () => {
  getProviderTable();
};
onMounted(() => {
  getTime();
  getProviderTable();
});
</script>

<template>
  <div class="page-content">
    <el-card>
      <PlusSearch v-model="form" searchText="搜索" resetText="重置" expand-text="展开" retractText="收起"
        :columns="searchColumns" :show-number="2" label-position="right" @search="handleSearch" @reset="handleRest" />
    </el-card>
    <el-card class="card">
      <div v-if="!showMonthTableDetail" class="operate">
        <el-button type="primary">导出</el-button>
      </div>
      <div v-else class="operate">
        <el-button type="primary" @click="recoverFn1">返回</el-button>
        <div class="text-center py-[10px] text-xl font-bold">
          全货明细表（{{ monthForm.kssj }}至{{ monthForm.jssj || "当前" }}）
        </div>
      </div>
      <PureTable v-if="!showMonthTableDetail" ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip
        :data="data" :columns="columns" @cell-click="handleCellClick" />
      <PureTable v-else ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip :data="monthListData"
        :columns="columns2" />
    </el-card>
    <el-card class="card">
      <div class="text-center py-[10px] text-xl font-bold">
        {{ form.dhnd }}年采购物料到货全货率
      </div>
      <div class="h-[400px]">
        <EChartsComponent :extraOptions="option" type="bar" />
      </div>
    </el-card>

    <el-card class="card">
      <!-- <div class="operate" v-if="!apiData4.length">
        <el-button type="primary">导出</el-button>
      </div> -->
      <div v-if="showProviderDetail" class="operate">
        <el-button type="primary" @click="recoverFn2">返回</el-button>
        <div class="text-center py-[10px] text-xl font-bold">
          {{ form.gysNmae }} 全货明细表（{{ form.kssj }}至{{
            form.jssj || "当前"
          }}）
        </div>
      </div>
      <PureTable v-if="!showProviderDetail" ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip
        :data="providerTableData" :pagination="pagination" :columns="columns3" @page-current-change="changePagination"
        @cell-click="handleCellClick2" />
      <PureTable v-else ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip
        :data="providerDetailList" :columns="columns4" />
    </el-card>
  </div>
</template>
<style lang="css" scoped>
.card {
  margin-top: 20px;
}

.operate {
  margin-bottom: 20px;
}
</style>
